<template>
  <div>
    <h1>自定义事件</h1>

    <AddItem @add="add" />
    <TodoList :todos="todos"  />
    <Status :todos="todos" @changeAllCheck="changeAllCheck" @clearAlldone="clearAlldone"/>
  </div>
</template>

<script>

import pubsub from "pubsub-js";
import AddItem from "./components/AddItem";
import Status from "./components/Status";
import TodoList from "./components/TodoList";
import Student from "./components/Student";

export default {
  name: 'App',
  components: { AddItem,Status,TodoList,Student},
  data(){
    return{
      todos:JSON.parse(localStorage.getItem("todos")) || []
      //   [
      //   // {id:"001",title:"吃饭",done:true },
      //   // {id:"002",title:"睡觉",done:false },
      //   // {id:"003",title:"学习",done:false },
      // ]
    }
  },
  methods:{
    showstuName(name){
      alert(name)
    },
    add(obj){
      this.todos.unshift(obj)
    },
    change(id){
      this.todos.forEach((todo)=>{
        if(todo.id==id){
          todo.done=!todo.done
          console.log(todo)
        }
      })
    },
    // deltodo(id){
    // 订阅时有个消息名，用_占位参数
    deltodo(_,id){
      this.todos = this.todos.filter((todo)=>{
        return todo.id !== id
      })
    },
    clearAlldone(){
      this.todos=this.todos.filter((todo)=>{
        return !todo.done
      })
    },
    changeAllCheck(value){
      this.todos.forEach((todo)=>{
        todo.done =value
      })
    }
  },
  watch:{
    todos:{
      deep:true,
      handler(value){
        localStorage.setItem("todos",JSON.stringify(value))
      }
    }
  },
  mounted() {
    this.$bus.$on('change',this.change)

    this.pubid=pubsub.subscribe('deltodo',this.deltodo)

    // this.$bus.$on('deltodo',this.deltodo)
  },
  beforeDestroy() {
    this.$bus.$off('change')
    // this.$bus.$off('deltodo')
    pubsub.unsubscribe(this.pubid)
  }
}
</script>
